<?php

namespace App\Console\Commands;

use App\Models\KangxiModel;
use App\Models\NameModel;
use Illuminate\Console\Command;
use Illuminate\Database\QueryException;

class Processor extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:processor';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @var string 姓
     */
    public static $LAST_NAME = "陈";
    public static $WUXING = ['水', '金'];
    /**
     * @var string[] 生肖冲突
     */
    public static $SHENGXIAO_YES = ['玉', '豆', '米', '艹', '禾', '山', '月', '人', '王', '口', '宀'];
    public static $SHENGXIAO_NO = ['彡', '巾', '衣', '采', '禾', '谷', '米', '豆', '虎', '山', '虍', '林'];
    //        $yes = ['山', '木', '金', '口', '田', '辶', '一','艹','禾','土','石‌','糸','纟'];
//        $no = ['虍', '水', '氵', '戈', '刀', '寅', '虔', '亥', '豕', '艹', '豆', '禾', '麦', '亻', '大', '灬', '刚', '剑'];


    public function handle()
    {
        $surname = KangxiModel::where('char', '=', Processor::$LAST_NAME)->first();
        if ($surname == null) {
            throw new \Exception("姓不能为空，先爬取数据");
        }
        $chars = KangxiModel::whereIn('wuxing', Processor::$WUXING)->where('jixiong', '吉')->get();
        $total = $chars->count();
        $bar = $this->output->createProgressBar($total * $total);

        $chars->each(function ($char) use ($chars, $surname, $bar) {
            $chars->each(function ($char2) use ($char, $surname, $bar) {
                // 保存
                $this->analyze($surname, $char2, $char);
                $bar->advance();
            });
        });

        $bar->finish();
    }

    private function analyze($xing, $middlename, $lastname)
    {
        $name = new NameModel();
        $name->name = $xing->char . $middlename->char . $lastname->char;
        $name->name_wuxing = $xing->wuxing . $middlename->wuxing . $lastname->wuxing;

        //汉字笔画
        $bihua_xing = $this->getBiHua($xing);
        $bihua_middlename = $this->getBiHua($middlename);
        $bihua_lastname = $this->getBiHua($lastname);


        if (!$bihua_xing || !$bihua_middlename || !$bihua_lastname) {
            $this->warn("名字计算失败 name:{$name->name},mid-name:{$bihua_middlename},last:{$bihua_lastname}");
            //计入失败名字
            return false;
        }

        //各格
        $name->tiange = $bihua_xing + 1;                        //天格
        $name->renge = $bihua_xing + $bihua_middlename;         //人格
        $name->dige = $bihua_middlename + $bihua_lastname;      //地格
        $name->zongge = $bihua_xing + $bihua_middlename + $bihua_lastname;  //总格
        $name->waige = $name->zongge - $name->renge + 1;      //外格
//        $name->waige = $bihua_lastname + 1;                     //外格

        //吉凶
        $name->tiange_jixiong = $this->shuli($name->tiange);
        $name->renge_jixiong = $this->shuli($name->renge);
        $name->dige_jixiong = $this->shuli($name->dige);
        $name->waige_jixiong = $this->shuli($name->waige);
        $name->zongge_jixiong = $this->shuli($name->zongge);

        //五行
        $name->tiange_wuxing = $this->wuxing($name->tiange)['wuxing'];
        $name->renge_wuxing = $this->wuxing($name->renge)['wuxing'];
        $name->dige_wuxing = $this->wuxing($name->dige)['wuxing'];
        $name->waige_wuxing = $this->wuxing($name->waige)['wuxing'];
        $name->zongge_wuxing = $this->wuxing($name->zongge)['wuxing'];

        //阴阳
        $name->tiange_yinyang = $this->wuxing($name->tiange)['yinyang'];
        $name->renge_yinyang = $this->wuxing($name->renge)['yinyang'];
        $name->dige_yinyang = $this->wuxing($name->dige)['yinyang'];

        //三才
        $name->sancai = $name->tiange_wuxing . $name->renge_wuxing . $name->dige_wuxing;
        $name->sancai_jixiong = $this->sancai($name->sancai);

        //生肖禁忌
        $name->shengxiao = $this->jingji($this->getBushou($middlename)) . $this->jingji($this->getBushou($lastname));

        $name->zhongzi = 'N';
        $name->sanzi = 'N';


        try {
            if ($name->save()) {
//                $this->info(
//                    "\t" . $name->name . 'OK'
//                );
            } else {
                $this->info(
                    "\t" . $name->name . 'FAILED'
                );
            }
        } catch (QueryException $e) {
            if ($e->getCode() == 23000) {
//                $this->info(
//                    "\t" . $name->name . 'already saved'
//                );
            } else {
                $this->error(
                    "\t" . $name->name . 'SAVE FAILED' . $e->getMessage()
                );
                sleep(10);
            }
        }

    }

    private function getBushou($charModel)
    {
        if ($charModel->jianti_bushou) {
            return $charModel->jianti_bushou;
        }
        if ($charModel->fanti_bushou) {
            return $charModel->fanti_bushou;
        }
        if ($charModel->bushou) {
            return $charModel->bushou;
        }
        return '';
    }

    /**
     * @param $charModel
     * 获取笔画
     */
    private function getBihua($charModel)
    {
        //处理康熙笔画
        if (is_numeric($charModel->kangxi_bihua)) {
            return $charModel->kangxi_bihua;
        }
        if ($charModel->kangxi_bihua) {
            $kangxi_bihua_arr = explode(',', $charModel->kangxi_bihua);

            if (count($kangxi_bihua_arr) == 1) {
                return trim($charModel->kangxi_bihua);
            }

            if (count($kangxi_bihua_arr) > 1) {
                $kangxizi_arr = explode(',', $charModel->kangxizi);
                for ($i = 0; $i < count($kangxizi_arr); ++$i) {
                    if ($charModel->char == $kangxizi_arr[$i]) {
                        return trim($kangxi_bihua_arr[$i]);
                    }
                }
                return $kangxi_bihua_arr[0];
            }
        }

        //如果没有康熙笔画
        //使用简体笔画
        if ($charModel->jianti_bushou_bihua > 0) {
            return $charModel->jianti_bushou_bihua;
        }

        //使用繁体笔画
        if ($charModel->fanti_bihua > 0) {
            return $charModel->fanti_bihua;
        }

        //使用笔画
        if ($charModel->bihua > 0) {
            return $charModel->bihua;
        }

        return false;   //这个情况不会出现,除非数据错误
    }


    private function jingji($bushou)
    {
        $flag = '';
        if (in_array($bushou, Processor::$SHENGXIAO_YES)) {
            $flag = '宜';
        }
        if (in_array($bushou, Processor::$SHENGXIAO_NO)) {
            $flag = '忌';
        }
        return $flag;
    }

    private function wuxing($num)
    {
        // 确保数值有效性
        $num = (int)$num;

        // 核心优化：%10取尾数
        $last_digit = $num % 10; // 直接获取尾数

        $wuxing = null;
        if ($last_digit === 1 || $last_digit === 2) {
            $wuxing = '木';
        } elseif ($last_digit === 3 || $last_digit === 4) {
            $wuxing = '火';
        } elseif ($last_digit === 5 || $last_digit === 6) {
            $wuxing = '土';
        } elseif ($last_digit === 7 || $last_digit === 8) {
            $wuxing = '金';
        } elseif ($last_digit === 9 || $last_digit === 0) { // 0即水
            $wuxing = '水';
        }

        return [
            'wuxing' => $wuxing,
            'yinyang' => ($last_digit % 2 == 0) ? '阴' : '阳'
        ];
    }

    private function shuli($num)
    {
        $head = [1, 3, 5, 6, 7, 8, 11, 13, 15, 16, 17, 18, 21, 23, 24, 25, 31, 32, 33, 35, 37, 39, 41, 45, 47, 48, 52, 57, 61, 63, 65, 67, 68, 71, 77, 81];
        $middle = [30, 36, 38, 49, 50, 51, 55, 58, 72, 73];

        if (in_array($num, $head)) {
            return '吉';
        }
        if (in_array($num, $middle)) {
            return '半吉';
        }
        return '凶';
    }

    private function sancai($name_wuxing)
    {
        $head = [
            '木木木', '木木火', '木木土', '木火木', '木火土', '木水木',
            '火木木', '火木火', '火木土', '火火木', '火土火', '火土土',
            '土火木', '土火土', '土土火', '土土土', '土土金', '土金土', '土金金',
            '金土土', '金土金', '金金土', '金水金',
            '水木木', '水木土', '水金土',
        ];
        $middle = [
            '木火火', '木土土',
            '火火火', '火土木',
            '土木木', '土木火', '土火火', '土火金',
            '金木土', '金土火', '金金水',
            '水木火', '水金金', '水水金',
        ];

        if (in_array($name_wuxing, $head)) {
            return '吉';
        }
        if (in_array($name_wuxing, $middle)) {
            return '半吉';
        }
        return '凶';
    }
}
